package org.oschina.api.user.bar.dao;

import java.util.List;
import org.oschina.Constants;
import org.oschina.api.BaseDAO;
import org.oschina.api.user.bar.model.UserBar;
import org.oschina.api.user.role.vo.UserBarVo;
import org.springframework.stereotype.Repository;

@Repository
public class UserBarDAO extends BaseDAO {

	private final String findVo[]={"id","icon","text","url","click","parent","`index`"};
	
	/**
	 * 返回	
	 * @return
	 */
	public List<UserBarVo> findVo()
	{
		return getQueryHelper().query_cache(findVo, null, new String[]{"ORDER BY `index`"}, null, UserBarVo.class,-1,-1);
	}
	
	/**
	 * 根据权限返回
	 * @param role
	 * @return
	 */
	public List<UserBarVo> findVoByRole(int role)
	{
		return getQueryHelper().query_cache(findVo, new String[]{"id IN (SELECT ubr.bar FROM "+Constants.DB_USER_BAR_ROLE+" ubr WHERE ubr.role=?)"}, 
				new String[]{"ORDER BY `index`"}, new Object[]{role}, UserBarVo.class,-1,-1);
	}
	
	/**
	 * 更新
	 * @param bar
	 * @return
	 */
	public int update(UserBar bar)
	{
		return (int) getQueryHelper().update_cache(new String[]{"icon=?","text=?","url=?","click=?","parent=?","`index`=?"}, new String[]{"id=?"}, 
				new Object[]{bar.getIcon(),bar.getText(),bar.getUrl(),bar.getClick(),bar.getParent(),bar.getIndex(),bar.getId()}, UserBarVo.class);
	}
	
	/**
	 * 创建
	 * @param bar
	 * @return
	 */
	public int create(UserBar bar)
	{
		return (int) getQueryHelper().insert_cache(new String[]{"id","icon","text","url","click","parent","`index`","create_time"},
				new Object[]{bar.getId(), bar.getIcon(), bar.getText(), bar.getUrl(), bar.getClick(),bar.getParent(),bar.getIndex(), bar.getCreate_time()}, UserBarVo.class);
	}
	
	/**
	 * 删除
	 * @param id
	 * @return
	 */
	public int delete(int id)
	{
		return (int) getQueryHelper().delete_cache(new String[]{"id=?"}, new Object[]{id}, UserBarVo.class);
	}
	
	/**
	 * 根据ID返回
	 * @param id
	 * @return
	 */
	public UserBarVo findVoById(int id)
	{
		UserBarVo barVo=(UserBarVo) getCacheHelper().hget(getKey(Constants.CACHE_USER_BAR, id), UserBarVo.class);
		if(barVo!=null)
			return barVo;
		
		return _findById(id);
	}
	private UserBarVo _findById(int id)
	{
		return (UserBarVo) getQueryHelper().queryForObject_cache(findVo, new String[]{"id=?"}, new Object[]{id}, UserBarVo.class);
	}
}